package cn.shengchao.examstar.ai.domain.event;

import cn.shengchao.examstar.ai.domain.model.studyplan.StudyPlanId;
import cn.shengchao.examstar.ai.domain.valueobject.DegreeOfMastery;
import cn.shengchao.examstar.ai.domain.valueobject.UserId;
import cn.shengchao.examstar.shared.domain.event.DomainEvent;
import lombok.Getter;

import java.time.LocalDateTime;
import java.util.Objects;

/**
 * 学习进度更新事件
 * 当学习计划的掌握程度发生变化时发布此事件
 */
@Getter
public class StudyProgressUpdatedEvent extends DomainEvent {
    
    private final StudyPlanId studyPlanId;
    private final UserId userId;
    private final DegreeOfMastery oldMastery;
    private final DegreeOfMastery newMastery;
    private final LocalDateTime occurredOn;
    
    public StudyProgressUpdatedEvent(StudyPlanId studyPlanId,
                                   UserId userId,
                                   DegreeOfMastery oldMastery,
                                   DegreeOfMastery newMastery) {
        this.studyPlanId = Objects.requireNonNull(studyPlanId, "学习计划ID不能为空");
        this.userId = Objects.requireNonNull(userId, "用户ID不能为空");
        this.oldMastery = oldMastery; // 可以为null，表示初始状态
        this.newMastery = Objects.requireNonNull(newMastery, "新掌握程度不能为空");
        this.occurredOn = LocalDateTime.now();
    }
    
    public LocalDateTime occurredOn() {
        return occurredOn;
    }
    
    /**
     * 判断是否为进步（掌握程度提升）
     */
    public boolean isImprovement() {
        if (oldMastery == null) {
            return true; // 从无到有算作进步
        }
        return newMastery.isHigherThan(oldMastery);
    }
    
    /**
     * 判断是否为退步（掌握程度下降）
     */
    public boolean isRegression() {
        if (oldMastery == null) {
            return false;
        }
        return oldMastery.isHigherThan(newMastery);
    }
    
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        StudyProgressUpdatedEvent that = (StudyProgressUpdatedEvent) o;
        return Objects.equals(studyPlanId, that.studyPlanId) &&
                Objects.equals(userId, that.userId) &&
                Objects.equals(oldMastery, that.oldMastery) &&
                Objects.equals(newMastery, that.newMastery) &&
                Objects.equals(occurredOn, that.occurredOn);
    }
    
    @Override
    public int hashCode() {
        return Objects.hash(studyPlanId, userId, oldMastery, newMastery, occurredOn);
    }
    
    @Override
    public String toString() {
        return "StudyProgressUpdatedEvent{" +
                "studyPlanId=" + studyPlanId +
                ", userId=" + userId +
                ", oldMastery=" + oldMastery +
                ", newMastery=" + newMastery +
                ", occurredOn=" + occurredOn +
                '}';
    }
}